import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { FormBuilder, UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms';
import { BehaviorSubject } from 'rxjs';
import { DefaultTypeEnum } from 'src/app/models/enums/default-type.enum';
import { EditMode } from 'src/app/models/enums/edit-mode.enum';
import { DictDto } from 'src/app/models/sys/dict.dto';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ApiService } from 'src/app/services/api.service';
import { Consts } from 'src/app/consts/consts';
import { AddDeptTypeParam } from 'src/app/models/param/add-dept-type.param';
import { UpdateDeptTypeParam } from 'src/app/models/param/update-dept-type.param';

const DEPT_TYPE = 'deptType';
const DICT_LABEL = 'dictLabel';
const REMARK = 'remark';

@Component({
  selector: 'app-add-dept-type',
  templateUrl: './add-dept-type.component.html',
  styleUrl: './add-dept-type.component.less'
})
export class AddDeptTypeComponent implements OnInit {
  @Input() modeSubject!: BehaviorSubject<{ mode: EditMode, deptType?: DictDto }>;

  @Output() addDeptTypeEvent = new EventEmitter<boolean>();

  deptType?: DictDto;
  modeEnum = EditMode;
  editMode = EditMode.ADD;

  // form fields
  addForm!: UntypedFormGroup;
  submitted = false;

  selectedDefault = DefaultTypeEnum.NOT_DEFAULT;

  constructor(private _api: ApiService,
    private _fb: FormBuilder,
    private _message: NzMessageService) { }

  ngOnInit(): void {
    this.createAddForm();
  }

  resetModal() {
    this.submitted = false;
    this.selectedDefault = DefaultTypeEnum.NOT_DEFAULT;
  }

  createAddForm() {
    this.addForm = this._fb.group({});
    this.addForm.addControl(DEPT_TYPE, new UntypedFormControl('', [Validators.minLength(2),
    Validators.maxLength(20), Validators.pattern('^[0-9a-zA-Z_]{1,}$')]));
    this.addForm.addControl(DICT_LABEL, new UntypedFormControl('', [Validators.minLength(2), Validators.maxLength(20)]));
    this.addForm.addControl(REMARK, new UntypedFormControl('', [Validators.maxLength(1024)]));

    this.modeSubject.subscribe((value) => {
      this.editMode = value.mode;

      if (value.mode === EditMode.ADD) {
        this.addForm.get(DEPT_TYPE)?.addValidators(Validators.required);
        this.addForm.get(DICT_LABEL)?.addValidators(Validators.required);
      } else {
        this.addForm.get(DEPT_TYPE)?.disable();
        this.deptType = value.deptType!;
        this.initParam(this.deptType);
      }
    });
  }

  initParam(groupType: DictDto) {
    this.addForm.get(DEPT_TYPE)?.patchValue(groupType.key);
    this.addForm.get(DICT_LABEL)?.patchValue(groupType.name);
    this.addForm.get(REMARK)?.patchValue(groupType.desc);
  }

  get fm() {
    return this.addForm.controls;
  }

  onCreate() {
    this.submitted = true;
    if (!this.addForm.valid) {
      return;
    }

    const param = new AddDeptTypeParam();
    param.dictLabel = this.addForm.get(DICT_LABEL)?.value;
    param.deptType = this.addForm.get(DEPT_TYPE)?.value;
    param.remark = this.addForm.get(REMARK)?.value;
    param.isDefault = this.selectedDefault;
    this._api.addDeptType(param).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK) {
        this._message.info("添加部门类型成功");
        this.resetModal();
        this.addDeptTypeEvent.emit(true); 
      } else {
        this._message.warning("添加部门类型失败 " + resp.message);
      }
    });
  }

  onUpdate() {
    this.submitted = true;
    if (!this.addForm.valid) {
      return;
    }
    if (this.deptType == null) {
      this._message.warning("未选中分组");
      return;
    }

    const param = new UpdateDeptTypeParam();
    param.id = this.deptType!.id!;
    param.deptType = this.addForm.get(DEPT_TYPE)?.dirty ? this.addForm.get(DEPT_TYPE)?.value : undefined;
    param.dictLabel = this.addForm.get(DICT_LABEL)?.dirty ? this.addForm.get(DICT_LABEL)?.value : undefined;
    param.remark = this.addForm.get(REMARK)?.dirty ? this.addForm.get(REMARK)?.value : undefined;

    this._api.updateDeptType(param).subscribe((resp) =>{
      if (resp.code == Consts.RESP_OK) {
        this._message.info("更新部门类型成功");
        this.resetModal();
        this.addDeptTypeEvent.emit(true); 
      } else {
        this._message.warning("更新部门类型失败 " + resp.message);
      }
    })
  }

  onSubmit(event: UIEvent) {
    event.preventDefault();

    if (this.editMode === EditMode.ADD) {
      this.onCreate();
    } else {
      this.onUpdate();
    }
  }
  
  onCancel(event: UIEvent) {
    event.preventDefault();

    this.resetModal();
    this.addDeptTypeEvent.emit(false);
  }
}
